/*
https://leetcode.cn/problems/stone-game-ii/solution/java-dong-tai-gui-hua-qing-xi-yi-dong-17xing-by-lg/
 */
public class Solution1140 {
    public int stoneGameII(int[] piles) {
        int sum=0;
        int[][] dp=new int[piles.length][piles.length+1];
        for (int i=piles.length-1;i>=0;i--){
            sum+=piles[i];
            for (int j=1;j<=piles.length;j++){
                if (i+2*j>=piles.length){
                    dp[i][j]=sum;
                }else{
                    for (int k=1;k<=2*j;k++){
                        dp[i][j]=Math.max(dp[i][j],sum-dp[i+k][Math.max(j,k)]);
                    }
                }
            }
        }
        return dp[0][1];
    }

    public static void main(String[] args) {
        System.out.println(new Solution1140().stoneGameII(new int[]{2,7,9,4,4}));
    }
}
